from odoo import fields, api, models
from odoo.exceptions import UserError

class InheritRpPayment(models.Model):
    _inherit = 'rp.payment'
    
    advance_document_code = fields.Char(string='前置单据编号', compute='compute_advance_document_code', store=True)
    
    @api.depends('advance_document_id','advance_document_id.field_name_id', 'advance_document_id.field_record_id')
    def compute_advance_document_code(self):
        for rec in self:
            rec.advance_document_code = False
            if rec.advance_document_id.field_name_id and rec.advance_document_id.field_record_id:
                record = self.env[rec.advance_document_id.field_name_id.model].sudo().search([('id', '=', rec.advance_document_id.field_record_id)])
                if record:
                    field = rec.advance_document_id.field_name_id.field_id.filtered(lambda x:x.name == 'code')
                    if field:
                        rec.advance_document_code = record.code
                    else:
                        field = rec.advance_document_id.field_name_id.field_id.filtered(lambda x:x.name == 'name')
                        if field:
                           rec.advance_document_code = record.name
